package main

import (
	"ScriptServer/models"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

func authValid() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Query("token")
		if tokenString == "" {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
		token,err := jwt.ParseWithClaims(tokenString, &models.CustomClaims{},func(token *jwt.Token) (interface{}, error) {
			if _,ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
			}
			return []byte("xiahaoran"), nil
		})
		if claims, ok := token.Claims.(*models.CustomClaims); ok && token.Valid{
			if err := claims.Valid();err == nil {
				fmt.Println(claims.ExpiresAt)
				c.Next()
			}else {
				fmt.Println(err)
				c.AbortWithStatus(http.StatusUnauthorized)
			}
		} else {
			fmt.Println(err)
			c.AbortWithStatus(http.StatusUnauthorized)
		}
	}
}